<template>
  <a-modal
    :title="modalTitle"
    width="800px"
    centered
    :visible="userOperationVisible"
    :maskClosable="false"
    @cancel="close"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="rules"
      v-bind="formLayout"
      class="inform-form"
      style="height:auto;"
    >
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="用户名" prop="loginName">
            <a-input v-model="form.loginName" :disabled="optFlag==2" :maxLength="16" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="密码" prop="password">
            <a-input-password ref="password" v-model="form.password" style="width:64%"></a-input-password>
            <a-button
              type="primary"
              @click="getDefaultPassword()"
              style="float:right;margin-top:4px"
            >初始密码</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="手机号码" prop="mobile">
            <a-input v-model="form.mobile" autocomplete="off" :maxLength="11" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item has-feedback label="邮箱" prop="email">
            <a-input v-model="form.email" autocomplete="off" />
          </a-form-model-item>
        </a-col>>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="群组管理" prop="unitId">
            <a-select show-search v-model="form.unitId" :filter-option="filterOption">
              <a-select-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.unitName"
              >{{item.unitName}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-model-item label="是否短信" prop="sendSms">
            <a-switch v-model="form.sendSms" />
          </a-form-model-item>
        </a-col>-->
      </a-row>
    </a-form-model>
    <template slot="footer">
      <a-button type="primary" @click="submitInform('form')">保存</a-button>
      <!-- <a-button type="danger" v-if="optFlag!==1">删除</a-button> -->
      <a-button @click="close">取消</a-button>
    </template>
  </a-modal>
</template>

<script>
import { commonUser } from "@/api/commonUser";
import { getDefaultPassword } from "@/api/system";
import { booleanConversion, numberConversion } from "assets/js/utils.js";
export default {
  props: {
    //关闭弹框
    closeFunc: {
      type: Function,
      default: () => {},
    },
    userOperationVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      //存储的所属独立机构id
      type: String,
      default: "",
    },
    modalTitle: {
      type: String,
      default: "",
    },
    optFlag: {
      type: Number,
      default: 1, //默认1是新增2是编辑
    },
    userId: {
      //当前用户id
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        id: "",
        email: "",
        password: "",
        mobile: "",
        loginName: "",
        sendSms: false,
        unitId: "",
      },
      formLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      rules: {
        mobile: [
          {
            max: 11,
            message: "长度不合法, 手机号限11位",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              const number = /^[0-9]+$/;
              if (value && !number.test(value)) {
                callback(new Error("只允许输入数字"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1(3|4|5|6|7|8)\d{9}$/,
            message: "请输入正确的手机号",
          },
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              const whiteSpace = /^[a-zA-Z0-9]{4,10}$/;
              if (value && !whiteSpace.test(value)) {
                callback(new Error("密码不能含有非法字符，长度在4-10之间"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        loginName: [
          {
            validator: (rule, value, callback) => {
              const regg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
              //const replaceReg = /[^\\x00-\\xff]/;
              //var len = value.replace(/[^\x00-\xff]/g, "aa").length;
              if (value && !regg.test(value)) {
                callback(new Error("请输入汉字/英文/数字, 不包含特殊符号"));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },

          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        unitId: [{ required: true, message: "请选择群组", trigger: "change" }],
      },
      //群组下拉框
      unitList: [],
    };
  },
  methods: {
    //初始化密码
    getDefaultPassword() {
      getDefaultPassword().then((res) => {
        this.form.password = res.data.data;
        this.$refs.password.visible = true;
      });
    },
    //获取用户信息
    getUserMessage() {
      console.log(this.userId);
      commonUser
        .getMessage(this.userId)
        .then((res) => {
          console.log("响应：", res);
          this.form.loginName = res.data.data.loginName;
          this.form.email = res.data.data.email;
          this.form.mobile = res.data.data.mobile;
          this.form.password = res.data.data.password;
          this.form.rootId = res.data.data.rootId;
          this.form.unitId = res.data.data.unitId;
          this.form.sendSms = booleanConversion(res.data.data.sendSms);
        })
        .catch((err) => {
          console.log(2222);
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //获取群组下拉
    getGroupList() {
      commonUser
        .getGroupList(this.id)
        .then((res) => {
          this.unitList = res.data.data;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    submitInform(formName) {
      //提交弹框表单
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        }
        var params = Object.assign({}, this.form);
        params.sendSms = numberConversion(params.sendSms);
        console.log(params);
        if (this.optFlag === 2) {
          params.id = this.userId;
          // 编辑提交
          this.updateSubmit(params);
        } else {
          //新增提交
          this.addSubmit(params);
        }
      });
    },
    updateSubmit(params) {
      commonUser
        .updateUser(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success(res.data.msg);
          this.$emit("updateUserInform");
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    addSubmit(params) {
      commonUser
        .addUser(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success(res.data.msg);
          this.$emit("updateUserInform");
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    //关闭弹框
    close() {
      this.$emit("closeFunc");
    },
    //form表单初始化
    handleReset() {
      this.form = {
        id: "",
        email: "",
        password: "",
        phoneNumber: "",
        loginName: "",
        sendSms: false,
        unitId: "",
      };
    },
  },
  watch: {
    userOperationVisible(n) {
      if (n) {
        console.log("optFlag：", this.optFlag);
        if (this.optFlag === 2) {
          this.getUserMessage();
        } else {
          this.handleReset("form");
        }
        this.getGroupList();
      } else {
        this.$refs["form"].resetFields();
      }
    },
  },
};
</script>

<style lang="stylus" scoped></style>